<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>event-correlation-update</title>
    <%@ include file="../include/common.jsp"%>
    <%@ include file="../include/tree.jsp"%>
    <%@ include file="../include/form.jsp"%>
    <%@ include file="../include/jbox.jsp"%>
    <%@ include file="../include/table.jsp"%>
	<style type="text/css">
		.ztree {border: 1px solid #617775;background: #fff;width:220px;height:360px;overflow-y:scroll;overflow-x:auto;}

		table.display td{
			white-space:normal;
		}
	</style>
	<script type="text/javascript">
		//从事件数据
		var str = '${data}';
		var data = str.split(",");
		//从事件序号
		var sNum = new Array();
		//从事件行ID
		var rowId = ${sNum};
		function back(){
			window.history.back();
		}
		function findObj(theObj, theDoc)
        {
              var p, i, foundObj;
             
              if(!theDoc) theDoc = document;
              if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
              {
                theDoc = parent.frames[theObj.substring(p+1)].document;
                theObj = theObj.substring(0,p);
              }
              if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
              for (i=0; !foundObj && i < theDoc.forms.length; i++)
                foundObj = theDoc.forms[theObj];
              for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
                foundObj = findObj(theObj,theDoc.layers.document);
              if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
             
              return foundObj;
        }

		function addRow(serialNumber,resName,eventTypeName,relationTypeName,linkResId,linkEventType,relationType){
				var tbl = findObj("testTable",document);             
			   	var newTR = tbl.insertRow(tbl.rows.length);
			    var newNameTD=newTR.insertCell(0);
			   	newNameTD.innerHTML = "&nbsp;&nbsp;&nbsp; <a href='javascript:Goto();' onclick='deleteRow(this,"+rowId+")'>删除</a>";         
			   	var newNameTD=newTR.insertCell(1);
			  	newNameTD.innerHTML = serialNumber;
			   	var newNameTD=newTR.insertCell(2);
			   	newNameTD.innerHTML = resName;
			   	var newNameTD=newTR.insertCell(3);
			  	newNameTD.innerHTML = eventTypeName;
			  	var newNameTD=newTR.insertCell(4);
			  	newNameTD.innerHTML = relationTypeName;
			  	var str =serialNumber+"|"+linkResId+"|"+linkEventType+"|"+relationType;
			  	data[rowId] = str;
			  	rowId = rowId+1;
			  	//改变奇偶颜色
			  	$('#testTable tbody tr:even').addClass('even');
				$('#testTable tbody tr:odd').addClass('odd');
		}
		function Goto() {
		}
		function deleteRow(obj,rowId){ 
			var tr = obj.parentNode.parentNode;
			var tbody = tr.parentNode;
			tbody.removeChild(tr);
			data[rowId] = "";
			$("#extendConfig").val('');
			//改变奇偶颜色
			$('#testTable tbody tr').removeClass('even');
			$('#testTable tbody tr').removeClass('odd');
			$('#testTable tbody tr:even').addClass('even');
			$('#testTable tbody tr:odd').addClass('odd');
		} 
		function addExpression(){
			var num = 0;
			for(var i = 0 ; i < data.length; i++){
				if(data[i] != null && data[i] != ""){
					sNum[num] = data[i].split("|")[0];
					num = num + 1;
				}
			}
		
			var ext= $("#extendConfig").val();
			ext=ext.replace(/&/g, "$");
		
			var url ="iframe:event/event-correlation!addExpression.action?sNum="+sNum+"&extendConfig="+ext;
			var opt = { title: "编辑表达式",width:600,height:400,buttons: {}};
			getTopWin(window).openjBox(url,opt,'addexpression-event-correlation',window);
		}
		function resCheckboxClick(){
			var str=document.getElementById("resCheckbox");
			if(str.checked == false){
				$("#resId").val('');
				$("#resName").val('');
				$("#eventTypeId").val('');
				$("#eventTypeName").val('');
			}
		}
		function delayCheckboxClick(){
			var str=document.getElementById("delay");
			if(str.checked == false){
				$("#isDelay").val(0);
			}else{
				$("#isDelay").val(1);
			}
		}
		function showResTree(){
			var str=document.getElementById("resCheckbox");
			if(str.checked == true){
				$.ajax({ 
					  type:"post", 
					  url:"${pageContext.request.contextPath}/resource/res-frame!resViewTree.action", 
					  data:"", 
					  datatype:"json",
					  success:function(data) { 
							var zNodes=eval(data);
							$.fn.zTree.init($("#treeDemo"), setting, zNodes);
								var obj = $("#resName");
								var offset = $("#resName").offset();
								$("#menuContent").css({left:offset.left + "px", top:offset.top + obj.outerHeight() + "px"}).slideDown("fast");
								$("body").bind("mousedown", onBodyDown);
					  } 
			     	})
	    	  }
		}
		var setting = {
				async: {
					enable: true,
					url:"${pageContext.request.contextPath}/resource/res-frame!resViewTree.action",
					dataType: "text",
					autoParam:["id"]
				},
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onClick: relNodeClick,
					onCheck: onCheck
				}
			};
			function relNodeClick(e, treeId, treeNode) {
				if(treeNode.id.substring(0,1) == 2){
					$("#resId").val(treeNode.id.split('|')[1]);
					$("#resName").val(treeNode.name);
					$("#mainEventType").val('');
					$("#eventTypeName").val('');
					hideMenu();
				}else{
					$("#resId").val('');
					$("#resName").val('请选择资源');	
					$("#mainEventType").val('');
					$("#eventTypeName").val('');
				}
				$("#resName").blur();
			}
			function onCheck(e, treeId, treeNode) {
				
			}
			function hideMenu() {
				$("#menuContent").fadeOut("fast");
				$("body").unbind("mousedown", onBodyDown);
			}
			function onBodyDown(event) {
				if (!(event.target.id == "menuBtn" || event.target.id == "resName" || $(event.target).parents("#menuContent").length>0)) {
					hideMenu();
				}
			}
		function editHelp(){
			$("#help").css({"top":$("#img").offset().top+$("#img").width()+"px", "left":$("#img").offset().left+$("#img").height()+"px", "visibility":"visible"})
		}
		function editHelpOut(){
			$("#help").css({"visibility":"hidden"})
		}
		$(function(){
			if('${eventCorrelationPolicyBean.eventCorrelationPolicy.resId}' != null && '${eventCorrelationPolicyBean.eventCorrelationPolicy.resId}' !=''){
				$("#resCheckbox").attr("checked", true);
			}
			$("#resName").val('${eventCorrelationPolicyBean.mainResName}');
			$("#resId").val('${eventCorrelationPolicyBean.eventCorrelationPolicy.resId}')
			$.formValidator.initConfig({formid:"myform"
		          ,onerror:function(msg){ }
		          ,onsuccess:function(){
		        	  	add();
		          		return false;
		          }
		    });
		    $("#delay").formValidator({onshow:"请输入数字   最大不能超过一天",onfocus:"请输入数字   最大不能超过一天",oncorrect:"输入正确"}).inputValidator({min:0,max:86400,type:"value",onerror:"请输入数字   最大不能超过一天"});
			$("#name").formValidator({onshow:"请输入字符串 长度(1-50)",onfocus:"请输入字符串 长度(1-50)",oncorrect:"输入正确"}).inputValidator({min:1,onerror:"不能为空"})
			.functionValidator({
			    fun:function(val,elem){
			    	    if(val.replace(/[^\x00-\xff]/g, "xx").length > 50){
			    	        return "长度超出最大范围";
			    	    }
			    	    return true;
				}
	  		}).ajaxValidator({
				type : "post",
				async : false,
				url:'${pageContext.request.contextPath}/event/event-correlation!checkName.action',
				data: "name="+encodeURI(encodeURI($("#name").val()))+"&oldName="+encodeURI(encodeURI('${eventCorrelationPolicyBean.eventCorrelationPolicy.name}')),
				datatype : "json",
				success : function(data){
					if(data== true)
					{
						return true;
					}else
					{
						return false;
					}
	   			},
			buttons: $("#button"),
			error: function(){alert("服务器没有返回数据，可能服务器忙，请重试");},
			onerror : "已经存在",
			onwait : "正在校验"
			});
		  $("#name").blur();
			$("#eventTypeName").formValidator({onshow:"请选择具体事件类别",onfocus:"请选择具体事件类别",oncorrect:"输入正确"}).inputValidator({min:1,onerror:"请选择具体事件类别"}).functionValidator({
			    fun:function(val,elem){
			        if(val=="请选择具体事件类别"){
					    return "请选择具体事件类别";
				    }else{
					    return true;
				    }
				}
			});
		});
		function showEventTypeTree(){
				$.ajax({ 
					  type:"post", 
					  url:"${pageContext.request.contextPath}/event/event-correlation!eventTypeViewTree.action?resId="+$("#resId").val(), 
					  data:"", 
					  datatype:"json",
					  success:function(data) { 
							var zNodes=eval(data);
							$.fn.zTree.init($("#treeDemo"), eventTypeSetting, zNodes);
								var obj = $("#eventTypeName");
								var offset = $("#eventTypeName").offset();
								$("#menuContent").css({left:offset.left + "px", top:offset.top + obj.outerHeight() + "px"}).slideDown("fast");
								$("body").bind("mousedown", onBodyDown);
					  } 
			     	})
		}
		var eventTypeSetting = {
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onClick: eventTypeNodeClick,
					onCheck: onCheck
				}
			};
			function eventTypeNodeClick(e, treeId, treeNode) {
				if(treeNode.id.indexOf('event') >= 0){
					$("#mainEventType").val(treeNode.id.substring(5,treeNode.id.length));
					$("#eventTypeName").val(treeNode.name);
					hideMenu();
				}else{
					$("#mainEventType").val('');
					$("#eventTypeName").val('请选择具体事件类别');
				}
				$("#eventTypeName").blur();
			}
			function add(){
				  //提交
				 $.ajax({
					   type: "POST", 
					   url: "${pageContext.request.contextPath}/event/event-correlation!save.action?data="+data, //请求的action
					   data: $("#myform").serialize(), //传的参数
					   dataType: 'json',
					   success: function(data){ //结果
						   if(data == true){
							   window.history.back();
						   }
						   else{
							   getTopWin(window).getMessageBox().alert("此规则已经被删除了,请返回列表并刷新","提示");
						   } 
					   }
				});
			}
			function addLink(){
				var num = 0;
				var sNum1 = new Array();
				for(var i = 0 ; i < data.length; i++){
					if(data[i] != null && data[i] != ""){
						sNum1[num] = data[i].split("|")[0];
						num = num + 1;
					}
				}
				var url ="iframe:event/event-correlation!addLink.action?sNum="+sNum1;
				var opt = { title: "新增从事件关联",width:570,height:300,buttons: {}};
				getTopWin(window).openjBox(url,opt,'addlink-event-correlation',window);
			}
			function addExpressionValue(expression) {
				var result = expression.replace( /^\s*/, '');
				while( result.indexOf("&amp;&amp;") != -1 ) {
					result = result.replace("&amp;&amp;","&&");
				}
				$("#extendConfig").val(result);
			} 
			function pageReset(){
				  $("#myform").get()[0].reset(); 
					if('${eventCorrelationPolicyBean.eventCorrelationPolicy.resId}' != null && '${eventCorrelationPolicyBean.eventCorrelationPolicy.resId}' !=''){
						$("#resCheckbox").attr("checked", true);
					}
					$("#resName").val('${eventCorrelationPolicyBean.mainResName}');
					$("#resId").val('${eventCorrelationPolicyBean.eventCorrelationPolicy.resId}')
			}
	</script>
  </head>
  
  <body>
         <h2 class="title-h2"><span>修改事件相关性</span></h2>
  		<div id="menuContent" style="display:none; position: absolute;z-index:100;">
			<ul id="treeDemo" class="ztree" style="margin-top:0; width:200px; height: 200px;"></ul>
		</div>
	  	<div id="help" style="position:absolute; visibility:hidden;border:2px solid #CCC;background-color:gray;">
			<label>示例(A事件和B、C中任一事件</label><br>
			<label>共同发生),即A&&(B||C):</label><br>
			<label>1、选择B,C事件</label><br>
			<label>2、点击"||"按钮</label><br>
			<label>3、点击"<<"按钮</label><br>
			<label>4、在事件列表中选择A,选择(B||C)</label><br>
			<label>5、点击"&&"按钮</label><br>
			<label>6、此时操作结果为A&&(B||C)</label><br>
			<label>点击提交即可</label><br>
		</div>
    	<form action="" id="myform" name="myform" method="post">
    		<table id="mytable" border="0" class="table_eidt">
    			<tr>
    				<th width="100px" class="td_left">
    					<span class="span_alert">*</span><label>规则名称</label>
    					<input id="id" name="id" value=${eventCorrelationPolicyBean.eventCorrelationPolicy.id} type="hidden">
    					<input id="status" name="status" value=${eventCorrelationPolicyBean.eventCorrelationPolicy.status} type="hidden">
    				</th>
    				<td class="td_right">
    					<input type="text" id="name" name="name" value="${eventCorrelationPolicyBean.eventCorrelationPolicy.name}" class="input_text">
    					<span id="nameTip" style="width: 150px"></span>
    				</td>
    			</tr>
    			<tr>
    				<th class="td_left">
    					<label>压制时间(秒)</label>
    				</th>
    				<td class="td_right">
    					<input id="delay" name="delay" value="${eventCorrelationPolicyBean.eventCorrelationPolicy.delay}"  style="width: 40px;"/>
    					<span id="delayTip" style="width: 200px"></span>
    				</td>
    			</tr>
    			<tr>
    				<th class="td_left">
    					<input type="checkbox" id="resCheckbox" onclick="resCheckboxClick();"><label>指定资源</label>
    				</th>
    				<td class="td_right">
    					<input id="resName" type="text" name="resName" readonly onclick="showResTree(); return false;" class="input_text tree_res"/>
    					<input id="resId" name="resId" type="hidden" >
    				</td>
    			</tr>
    			<tr>
    				<th class="td_left">
    					<span class="span_alert">*</span><label>主事件类别</label>
    				</th>
    				<td class="td_right">
	    				<input id="eventTypeName" type="text" name="eventTypeName" readonly value=${eventCorrelationPolicyBean.mainEventTypeName} onclick="showEventTypeTree();" class="input_text tree_res"/>
	    				<input id="mainEventType" name="mainEventType" type="hidden" value=${eventCorrelationPolicyBean.eventCorrelationPolicy.mainEventType}>
	    				<span id="eventTypeNameTip" style="width: 150px"></span>
    				</td>
    			</tr>
    			<tr>
    				<th class="td_left">
    					<label>从事件关联</label>
    				</th>
    				<td class="td_right">
    					<div style="padding: 2px">
					 		<a href="javascript:addLink();">新增</a>
						</div>
						<div>
							<table id="testTable" cellpadding="0" cellspacing="0" class="display dataTable">
									<thead>
										<tr>
											<th width="86" class="sorting_disabled">操作</th>
											<th width="100" class="sorting_disabled">序号</th>
											<th width="200" class="sorting_disabled">指定资源</th>
											<th class="sorting_disabled">从事件类别</th>
											<th width="100" class="sorting_disabled">关系类型</th>
										</tr>
									</thead>
									<tbody>	
										<c:forEach items="${eventCorrelationLinkList}" var="e" varStatus="status">
											<c:if test="${(status.index+1) mod 2 !=0}">
												<tr class="even">
													<td>
														&nbsp;&nbsp;&nbsp; <a href='javascript:Goto();' onclick='deleteRow(this,${e.sNum})'>删除</a>
													</td>
													<td>
														${e.eventCorrelationLink.serialNumber}
													</td>
													<td>
														${e.resName}				
													</td>
													<td>
														${e.eventTypeLinkName}
													</td>
													<td>
														${e.resRelationName}
													</td>
												</tr>
											</c:if>
											<c:if test="${(status.index+1) mod 2 ==0}">
												<tr class="odd">
													<td>
														&nbsp;&nbsp;&nbsp; <a href='javascript:Goto();' onclick='deleteRow(this,${e.sNum})'>删除</a>
													</td>
													<td>
														${e.eventCorrelationLink.serialNumber}
													</td>
													<td>
														${e.resName}				
													</td>
													<td>
														${e.eventTypeLinkName}
													</td>
													<td>
														${e.resRelationName}
													</td>
												</tr>
											</c:if>
										</c:forEach>
									</tbody>
							</table>
						</div>
						<div>
							<input type="text" id="extendConfig" name="extendConfig" style="width: 500px" readonly="readonly" value=${eventCorrelationPolicyBean.eventCorrelationPolicy.extendConfig}>
							<a href="javascript:addExpression();">编辑</a>
							<img src="/bsm/style/default/bsm/images/u90_original.gif" onmousemove="editHelp();" onmouseout="editHelpOut();" id="img">
						</div>
    				</td>
    			</tr>
    			<tr>
    				<th class="td_left">
    					<label>规则说明</label>
    				</th>
    				<td class="td_right">
    					<textarea style="width: 600px;height: 80px;" id="memo" name="memo">${eventCorrelationPolicyBean.eventCorrelationPolicy.memo}</textarea>
    				</td>	
    			</tr>
    		</table>
    		<div style="margin-left:150px; margin-top:5px;">
		    	<button type="submit" id="button" name="button" class="btn-4">保存</button>
		    	<button type="button" class="btn-4" onclick="pageReset();">重置</button>
		    	<button type="button" onclick="back();" class="btn-4">返回</button>
    		</div>
    	</form>
  </body>
</html>
